﻿using NUnit.Framework;
using ScottPlot;
using Color = ScottPlot.Color;

namespace WordStudy20250123.T002;

[TestFixture]
class ChartTest02
{
    [Test]
    public void Test01()
    {
        var xValues = Enumerable.Range(0, 100).Select(x => (double)x).ToList();

        var series = new List<DataSeries>
       {
           new DataSeries
           {
               YValues = Generate.Sin(100).ToList(),
               Label = "正弦波",
               YAxisLabel = "振幅（左轴）",
               Color = Color.FromARGB(0xFF0000FF) // 修复：使用 Color.FromARGB 方法创建蓝色  
           },
           new DataSeries
           {
               YValues = Generate.Cos(100).ToList(),
               Label = "余弦波",
               YAxisLabel = "振幅（右轴）",
               Color = Color.FromARGB(0xFFFF0000), // 修复：使用 Color.FromARGB 方法创建红色  
               UseRightAxis = true
           }
       };

        string outputPath = @"D:\data\WordStudy20250123\ChartTest01\dual_axis_chart.png";
        ChartGenerator.GenerateDualAxisLineChart(
            xValues: xValues,
            series: series,
            chartTitle: "双Y轴示例图表",
            xAxisTitle: "时间（秒）",
            outputPath: outputPath);
    }
}

public static class ChartGenerator
{
    /// <summary>
    /// 生成带有双Y轴的折线图
    /// </summary>
    /// <param name="xValues">X轴数据（共享）</param>
    /// <param name="series">数据系列集合</param>
    /// <param name="chartTitle">图表标题</param>
    /// <param name="xAxisTitle">X轴标题</param>
    /// <param name="outputPath">输出文件路径</param>
    /// <param name="width">图片宽度（默认800）</param>
    /// <param name="height">图片高度（默认500）</param>
    /// <param name="fontName">字体名称（默认宋体）</param>
    public static void GenerateDualAxisLineChart(
        List<double> xValues,
        List<DataSeries> series,
        string chartTitle,
        string xAxisTitle,
        string outputPath,
        int width = 800,
        int height = 500,
        string fontName = "宋体")
    {
        ValidateInput(xValues, series);

        var plt = new Plot();
        ConfigureFonts(plt, fontName);
        AddDataSeries(plt, xValues, series);
        ConfigureAxes(plt, series);
        ConfigureChartTitles(plt, chartTitle, xAxisTitle);
        plt.SavePng(outputPath, width, height);
    }

    private static void ValidateInput(List<double> xValues, List<DataSeries> series)
    {
        if (xValues == null || xValues.Count == 0)
            throw new ArgumentException("X轴数据不能为空");

        if (series == null || series.Count == 0)
            throw new ArgumentException("至少需要提供一个数据系列");

        foreach (var s in series)
        {
            if (s.YValues.Count != xValues.Count)
                throw new ArgumentException($"数据系列 '{s.Label}' 的Y轴数据长度与X轴不一致");
        }
    }

    private static void ConfigureFonts(Plot plt, string fontName)
    {
        var titleStyle = plt.Axes.Title.Label;
        titleStyle.FontName = fontName;
        titleStyle.FontSize = 24;

        foreach (var axis in plt.Axes.GetAxes())
        {
            axis.Label.FontName = fontName;
            axis.Label.FontSize = 18;
            axis.TickLabelStyle.FontName = fontName;
            axis.TickLabelStyle.FontSize = 16;
        }
    }

    private static void AddDataSeries(Plot plt, List<double> xValues, List<DataSeries> series)
    {
        foreach (var s in series)
        {
            var scatter = plt.Add.Scatter(xValues.ToArray(), s.YValues.ToArray());
            //scatter.Label = s.Label;
            
            scatter.LineWidth = 2;
            scatter.MarkerShape = MarkerShape.None;
            scatter.Color = s.Color;

            // 配置Y轴
            var yAxis = s.UseRightAxis ? plt.Axes.Right : plt.Axes.Left;
            yAxis.Label.Text = s.YAxisLabel;
            yAxis.Label.ForeColor = s.Color;
            yAxis.TickLabelStyle.ForeColor = s.Color;
        }
    }

    private static void ConfigureAxes(Plot plt, List<DataSeries> series)
    {
        // 自动调整坐标轴范围
        plt.Axes.AutoScale();

        // 如果存在右侧轴系列，确保右侧轴可见
        if (series.Any(s => s.UseRightAxis))
        {
            //plt.Axes.Right.Show();
            plt.Axes.Right.IsVisible = true;            
            //plt.Axes.Right.Ticks(true);
            plt.Axes.Right.TickLabelStyle.IsVisible = true;
        }
    }

    private static void ConfigureChartTitles(Plot plt, string chartTitle, string xAxisTitle)
    {
        plt.Title(chartTitle);
        plt.XLabel(xAxisTitle);
        //plt.Legend(true, Alignment.UpperRight);
        plt.Legend.Alignment = Alignment.UpperRight;
    }
}

/// <summary>
/// 数据系列配置类
/// </summary>
public class DataSeries
{
    /// <summary>
    /// Y轴数据值
    /// </summary>
    public List<double> YValues { get; set; }

    /// <summary>
    /// 数据系列显示名称
    /// </summary>
    public string Label { get; set; }

    /// <summary>
    /// Y轴标签说明
    /// </summary>
    public string YAxisLabel { get; set; }

    /// <summary>
    /// 线条颜色（默认蓝色），修复：使用 Color.FromARGB 方法创建蓝色  
    /// </summary>
    public Color Color { get; set; } = Color.FromARGB(0xFF0000FF);

    /// <summary>
    /// 是否使用右侧Y轴（默认false）
    /// </summary>
    public bool UseRightAxis { get; set; } = false;
}